package com.blockchain.console.service.content.achieve;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.security.auth.login.LoginException;

import com.blockchain.common.enums.QuestionType;
import com.blockchain.console.config.ConsoleConst;
import com.blockchain.console.service.content.QuestionManage;
import com.blockchain.console.service.content.entity.QuestionRecord;
import com.blockchain.console.service.content.query.QuestionQuery;
import com.blockchain.framework.data.sql.SQLConnectionProvider;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.exception.ParameterException;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.ItemParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.util.StringHelper;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.variables.P2PConst;

public class QuestionManageImpl extends AbstractInformationService implements QuestionManage{

	public static class QuestionManageFactory implements
	ServiceFactory<QuestionManage> {
		@Override
		public QuestionManage newInstance(ServiceResource serviceResource) {
			return new QuestionManageImpl(serviceResource);
		}
	}
	public QuestionManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	protected static final ItemParser<QuestionRecord> ITEM_PARSER = new ItemParser<QuestionRecord>() {

		@Override
		public QuestionRecord parse(ResultSet rs) throws SQLException {
			QuestionRecord question = null;
			if (rs.next()) {
				question=new QuestionRecord();
				question.id=rs.getInt(1);
				question.qt=EnumParser.parse(QuestionType.class, rs.getString(2));
				question.question=rs.getString(3);
				question.hd=rs.getString(4);
				question.tjsj=rs.getTimestamp(5);
				question.name=rs.getString(6);
				question.pxz=rs.getInt(7);
				question.questionEn=rs.getString(8);
				question.hdEn=rs.getString(9);
				question.questionTw=rs.getString(10);
				question.hdTw=rs.getString(11);
			}
			return question;
		}
	};
	
	@Override
	public PagingResult<QuestionRecord> search(String question,QuestionType qt, Paging paging)
			throws Throwable {
		SQLConnectionProvider sqlConnectionProvider = getSQLConnectionProvider();
		ArrayList<Object> parameters = new ArrayList<>();
		StringBuffer s = new StringBuffer();
		s.append("SELECT T5022.F01 id,T5022.F02 qt,T5022.F03 question,T5022.F04 tjsj ,"
				+ "T5022.F07 pxz ,t7.F02 name, T5022.F08, T5022.F09 FROM T5022 ");
		s.append(" LEFT JOIN "+ ConsoleConst.DB_CONSOLE + ".T7011 t7 ON T5022.F05=t7.F01 WHERE 1=1 ");
		if (!StringHelper.isEmpty(question)) {
			s.append(" AND T5022.F03 LIKE ? ");
			parameters.add(sqlConnectionProvider.allMatch(question));
		}
		if(qt!=null){
			s.append(" AND T5022.F02 = ?");
			parameters.add(qt);
		}
		s.append(" ORDER BY T5022.F07 ASC,T5022.F04 DESC ");
		return selectPaging(getConnection(P2PConst.DB_INFORMATION), new ArrayParser<QuestionRecord>() {

			ArrayList<QuestionRecord> list = new ArrayList<QuestionRecord>();
			@Override
			public QuestionRecord[] parse(ResultSet rs)
					throws SQLException {
				while(rs.next()){
					QuestionRecord questionRecord = new QuestionRecord();
					questionRecord.id=rs.getInt(1);
					questionRecord.qt=QuestionType.valueOf(rs.getString(2));
					questionRecord.question=rs.getString(3);
					questionRecord.tjsj=rs.getTimestamp(4);
					questionRecord.pxz=rs.getInt(5);
					questionRecord.name=rs.getString(6);
					questionRecord.questionEn=rs.getString(7);
					questionRecord.questionTw=rs.getString(8);
					list.add(questionRecord);
				}
				return list.toArray(new QuestionRecord[list.size()]);
			}
		}, paging, s.toString(), parameters);
	}

	@Override
	public int addQuestion(QuestionQuery query) throws Throwable {
		checkInfo(query);
		
		serviceResource.openTransactions();
		try(Connection connection = getConnection()){
			int id=insert(connection, 
					"INSERT INTO T5022 SET F02=?,F03=?,F08=?,F09=?,F04=?,F05=?,F06=?,F07=? "
					, query.getType(), query.getQuestion(),query.getQuestionEn(),query.getQuestionTw(),
					query.getTjsj(),serviceResource.getSession().getAccountId(),query.getPxz(),query.getPxz());
			execute(connection, "INSERT INTO T5022_1 SET F01 = ?, F02 = ?, F03 = ?, F04 = ?", id,
					query.getHd(), query.getHdEn(), query.getHdTw());
			return id;
		
		}
	}

	@Override
	public void delete(int... ids) throws Throwable {
		if (ids == null || ids.length == 0) {
			return;
		}
		serviceResource.openTransactions();
		try (Connection connection = getConnection()) {
			//删除内容
			try (PreparedStatement pstmt = connection
					.prepareStatement("DELETE FROM T5022_1 WHERE F01 = ?")) {
				for (int id : ids) {
					if (id <= 0) {
						continue;
					}
					pstmt.setInt(1, id);
					pstmt.addBatch();
				}
				pstmt.executeBatch();
			}
			//删除记录
			try (PreparedStatement pstmt = connection
					.prepareStatement("DELETE FROM T5022 WHERE F01 = ?")) {
				for (int id : ids) {
					if (id <= 0) {
						continue;
					}
					pstmt.setInt(1, id);
					pstmt.addBatch();
				}
				pstmt.executeBatch();
			}
		}
	}

	@Override
	public void updateQuestion(QuestionQuery query, int id) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("ID异常");
		}
		checkInfo(query);
		
		try(Connection connection=getConnection()){
			try(PreparedStatement ps=connection
					.prepareStatement("SELECT F01 FROM T5022 WHERE F01=?  ")){
				ps.setInt(1, id);
				try(ResultSet rs=ps.executeQuery()){
					if (!rs.next()) {
						throw new LoginException("问题不存在.");
					}
				}
			}
			// 修改问题信息
			execute(connection,
				"UPDATE T5022 SET F02=?,F03=?,F08=?,F09=?,F04=?,F05=?,F07=? WHERE F01 = ?",
				query.getType(), query.getQuestion(),query.getQuestionEn(),query.getQuestionTw(),
				query.getTjsj(),serviceResource.getSession().getAccountId(),query.getPxz(),id);
			// 修改内容
			execute(connection, "UPDATE T5022_1 SET F02=?,F03=?,F04=? WHERE F01 = ?",
				query.getHd(), query.getHdEn(), query.getHdTw(), id);
		
		}
	}

	private void checkInfo(QuestionQuery query) throws Throwable {
		if(query!=null){
			int queryIndex=query.getPxz();
			if(queryIndex<1){
				throw new ParameterException("排序值不能小于或等于0");
			}
			if (StringHelper.isEmpty(query.getQuestion())) {
				throw new ParameterException("问题不能为空");
			}
			if (query.getQuestion().length() > 50) {
				throw new ParameterException("问题不能超过50个字符.");
			}
			if(isMultiLang()) {
				if (StringHelper.isEmpty(query.getQuestionEn())) {
					throw new ParameterException("问题(英文)不能为空");
				}
				if (query.getQuestionEn().length() > 50) {
					throw new ParameterException("问题(英文)不能超过50个字符.");
				}
				if (StringHelper.isEmpty(query.getQuestionTw())) {
					throw new ParameterException("问题(繁体)不能为空");
				}
				if (query.getQuestionTw().length() > 50) {
					throw new ParameterException("问题(繁体)不能超过50个字符.");
				}
				if (StringHelper.isEmpty(query.getHdEn())) {
					throw new ParameterException("回答(英文)不能为空");
				}
				if (StringHelper.isEmpty(query.getHdTw())) {
					throw new ParameterException("回答(繁体)不能为空");
				}
			}
			QuestionType qt=query.getType();
			if (qt==null) {
				throw new ParameterException("问题类型不能为空");
			}
			if (StringHelper.isEmpty(query.getHd())) {
				throw new ParameterException("回答不能为空");
			}
		}
	}

	@Override
	public QuestionRecord getQuestion(int id) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("ID异常");
		}
		StringBuffer s = new StringBuffer();
		s.append("SELECT T5022.F01 id,T5022.F02 qt,T5022.F03 question,T5022_1.F02 hd,T5022.F04 tjsj,t7.F02 cjz,T5022.F07 pxz ,"
				+ "T5022.F08 questionEn,T5022_1.F03 hdEn,T5022.F09 questionTw,T5022_1.F04 hdTw FROM T5022 ");
		s.append(" LEFT JOIN T5022_1 ON T5022.F01=T5022_1.F01 ");
		s.append(" LEFT JOIN "+ ConsoleConst.DB_CONSOLE + ".T7011 t7 ON T5022.F01=t7.F01 WHERE T5022.F01=?");
		
		return select(getConnection(), ITEM_PARSER, s.toString(), id);
	}

	@Override
	public QuestionRecord getQueryIndex(int pxz,QuestionType questionType) throws Throwable {
		if (pxz <= 0) {
			throw new ParameterException("排序值异常");
		}
		StringBuffer s = new StringBuffer();
		s.append("SELECT T5022.F07 pxz FROM T5022 WHERE T5022.F07=? AND T5022.F02=? ");
		
		return select(getConnection(), new ItemParser<QuestionRecord>() {
			@Override
			public QuestionRecord parse(ResultSet rs) throws SQLException {
				QuestionRecord question = null;
				if (rs.next()) {
					question=new QuestionRecord();
					question.pxz=rs.getInt(1);
				}
				return question;
			}
		}, s.toString(), pxz,questionType);
	}

	@Override
	public void updateQuestionPxz(int id, int pxz) throws Throwable {
		if (id <= 0) {
			throw new ParameterException("ID异常");
		}
		if (pxz < 0) {
			throw new ParameterException("排序值不能小于0");
		}
		execute(getConnection(),"UPDATE T5022 SET F07=? WHERE F01 = ?",pxz,id);

	}

	public boolean isMultiLang() {
		return this.serviceResource.getSystemDefine().isMulitLanguage();
	}
	
}
